using System;
using System.Linq;
using System.Xml.Linq;
using NetQueryLib.Expressions;

namespace NetQueryLib.Expressions
{
	public class ClassNameSelectorExpression : SelectorExpression
	{
		public ClassNameSelectorExpression(string selector) : base(selector)
		{
		}

		private string ElementName
		{
			get
			{
				return Selector.Substring(0, Selector.IndexOf("."));
			}
		}

		private string ClassName
		{
			get
			{
				return Selector.Substring(Selector.IndexOf(".") + 1);
			}
		}

		public override bool Filter(XElement element)
		{
			var elementName = String.IsNullOrEmpty(ElementName) ? element.Name.LocalName : ElementName;
			var className = element.Attribute("class");

			if (className == null)
				return false;

			return elementName == element.Name.LocalName && className.Value.Split(' ').Any(@class => @class == ClassName);
		}
	}
}